'use strict';

var debug = require('debug'),
  log = debug('yozh:mw:log'),
  error = debug('yozh:mw:error'),
  verbose = debug('yozh:mw:verbose');

/**
 * requestCache middleware
 * @param  {Object} opts options
 * @return {Function} ES6 generator function
 */
module.exports = function(opts) {
  var middleware = function *requestCache(next) {
    var method = this.request.method;
    if (method === 'GET' || method === 'get' || method === 'Get') {
      // if client has a cache;
      if (this.request.fresh) {
        this.response.status = 304;
        return;
      }
      // find a redis cache like 'GET/v1/index?test=test';
      var res = yield opts.cache.get(
        this.request.method + this.path + this.querystring);
      if (res === this.get('If-Modified-Since')) {
        // no updated since the last query
        this.response.status = 304;
        return;
      }
    } else if (method === 'PUT' || method === 'put' || method === 'Put' ||
        method === 'DELETE' || method === 'delete' || method === 'Delete') {
      // set update entity id to body, this is mongodb objectId;
      var id = this.request.body._id;
      if (id) {
        var wres = yield opts.cache.get(id);
        if (wres !== this.get('If-Modified-Since')) {
          // before this has been modified;
          this.response.status = 400;
          return;
        }
      } else {
        // this.request.body miss param;
        this.response.status = 400;
        return;
      }
    }

    // this.log.info('This request fresh is: %s, since: %s, Etag: %s, res: %s',
    //   this.request.fresh, this.get('If-Modified-Since'),
    //   this.get('Etag'), res);
    verbose('This request fresh is: ', this.request.fresh,
      'since: ', this.get('If-Modified-Since'),
      'Etag: ', this.get('Etag'), 'res: ');
    yield next;
  };
  return middleware;
};
